package kz.vokebuz.demo;

import java.util.ArrayList;
import java.util.List;

import kz.vokebuz.demo.db.DbAdapter;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class SmsReciver extends BroadcastReceiver {
	Context thisContext;
	@Override
	public void onReceive(Context context, Intent intent) {
		 thisContext = context;
		   
		 Bundle bundle = intent.getExtras();

			SmsMessage[] msgs = null;
			if (bundle != null && bundle.containsKey("pdus")) {
				Object[] pdus = (Object[]) bundle.get("pdus");
				if (pdus != null) {
					List<SmsMmsMsg> messages = null;
					msgs = new SmsMessage[pdus.length];
					for (int i = 0; i < pdus.length; i++) {
						msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
					}
					for (int i = 0; i < msgs.length; i++) {

						messages = new ArrayList<SmsMmsMsg>();
						SmsMmsMsg msg = new SmsMmsMsg();

						msg.setMessageBody(msgs[0].getMessageBody());
						msg.setMsgType(0); // Sms type ;
						msg.setMsgOriginator(msgs[0].getDisplayOriginatingAddress());
						msg.setTimeStamp(msgs[0].getTimestampMillis());
						msg.setStatusReport(msgs[0].isStatusReportMessage());
						messages.add(msg);
					}
					writeToSqlite(messages);
				}
			}
		 
	                
	}
	
	private void writeToSqlite(List<SmsMmsMsg> msgs) {
		DbAdapter dbAdapter = new DbAdapter(thisContext);
        dbAdapter.open();
		int count = msgs.size();
		for (int i = 0; i < count; i++) {
			long restl = dbAdapter.addRow(msgs.get(i));
			if (restl == 0) {

			}
		}
	}
}
